<template>
  <div class="verify_page">
    <div>
      <el-tabs v-model="tab" type="border-card" class="demo-tabs">
        <el-tab-pane label="登录" name="login"></el-tab-pane>
        <el-tab-pane label="注册" name="register"></el-tab-pane>
      </el-tabs>
      <el-form
        ref="formRef"
        :model="from"
        :rules="rules"
        label-width="80px"
        class="form_wrap"
      >
        <el-form-item label="账号" prop="username">
          <el-input v-model="from.username" placeholder="请输入账号" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="from.password"
            type="password"
            placeholder="请输入密码"
          />
        </el-form-item>
        <el-form-item
          v-if="btnText === '注册'"
          label="确认密码"
          prop="epassword"
        >
          <el-input
            v-model="from.epassword"
            type="password"
            placeholder="请确认密码"
          />
        </el-form-item>
        <el-form-item>
          <el-button @click="submit">{{ btnText }}</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts" name="login-notcache">
import { ref, reactive, computed, watch } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { Md5 } from "ts-md5";
import useUserStore from "@/store/user";
import type { IUser } from "@/store/user";
import { register, login } from "@/api/user";

interface IVerify {
  msg: string;
  data: IUser;
}

const router = useRouter();
const userStore = useUserStore();
const formRef = ref<FormInstance>();
const from = reactive({
  username: "",
  password: "",
  epassword: "",
});
const tab = ref<"login" | "register">("login");
const btnText = computed(() => (tab.value === "login" ? "登录" : "注册"));
watch(tab, () => {
  formRef.value?.resetFields();
});
const submit = () => {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        const md5 = new Md5();
        md5.appendAsciiStr(from.password);
        const params = {
          username: from.username,
          password: md5.end(),
        };
        let res: IVerify;
        if (tab.value === "login") {
          res = await login<any, IVerify>(params);
          userStore.setToken(res.data.token);
          userStore.setUser(res.data);
          router.replace({ path: "/" });
        } else {
          res = await register<any, IVerify>(params);
          tab.value = "login";
        }
        ElMessage.success(res.msg);
      } catch (error) {
        console.log("validate error", error);
      }
    }
  });
};

// 验证
const validateName = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error("请输入账号"));
  }
  if (!/^[a-zA-Z]{6,8}$/.test(value)) {
    return callback(new Error("请输入6-8位字母"));
  }
  callback();
};
const validatePass = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请输入密码"));
  } else {
    if (!/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$/.test(value)) {
      return callback(new Error("请输入8-16位数字和字母"));
    }
    if (from.epassword !== "") {
      formRef.value?.validateField("epassword", () => null);
    }
    callback();
  }
};
const validateEpass = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请再次输入密码"));
  } else if (value !== from.password) {
    callback(new Error("两次输入密码不一致!"));
  } else {
    callback();
  }
};
interface RuleForm {
  username: string;
  password: string;
  epassword: string;
}
const rules = reactive<FormRules<RuleForm>>({
  username: [{ validator: validateName, trigger: ["blur", "change"] }],
  password: [{ validator: validatePass, trigger: ["blur", "change"] }],
  epassword: [{ validator: validateEpass, trigger: ["blur", "change"] }],
});
</script>
<style lang="scss" scoped>
.verify_page {
  display: flex;
  justify-content: center;
  padding-top: 20vh;
}
.form_wrap {
  padding-top: 20px;
}

::v-deep .el-tabs__content {
  padding: 0;
}
::v-deep .el-tabs__nav {
  width: 100% !important;
}
::v-deep .el-tabs__item {
  width: 50% !important;
  padding: 0;
  text-align: center;
}
</style>
